import React, { useEffect, useState } from "react";
import "./App.css";
import { Upload, Button, message, Row, Col, Modal } from "antd";
import { ExclamationCircleFilled } from '@ant-design/icons';
import { RcFile } from "antd/es/upload/interface";
import axios from "axios";

const { confirm } = Modal;
interface ObjectState {
  name: string;
  url: string;
}

function App() {
  const [objects, setObjects] = useState<ObjectState[]>([]);
  const beforeUpload = (file: RcFile, fileList: RcFile[]) => {
    const { name, size, type } = file;
    // 检测是不是图片
    if (!type.includes("image")) {
      message.error("只可以上传图片");
      return Upload.LIST_IGNORE;
    }
    // 检测图片大小  规定小于2MB
    if (size > 2 * 1024 * 1024) {
      message.error("上传的图片不可以超过2MB");
      return Upload.LIST_IGNORE;
    }
  };

  const fetchData = async () => {
    const resp = await axios.get("/api/upload/list");
    setObjects(resp.data.data.objects);
  };

  const handleDelete = (name: string) => {
    confirm({
      title: "确定要删除此文件吗",
      icon: <ExclamationCircleFilled />,
      content: "警告：删除之后无法恢复！！！",
      okText: '确定删除',
      cancelText: '取消删除',
      async onOk() {
        // 请求删除
        const resp = await axios.delete('/api/upload/delete', { params: { name } });
        fetchData()
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="App">
      <Upload beforeUpload={beforeUpload} action="/api/upload">
        <Button type="primary">上传文件</Button>
      </Upload>
      <Row>
        {objects.map((v, i) => {
          return (
            <Col span={6} style={{ padding: 6 }} key={i}>
              <img
                src={v.url}
                key={i}
                alt=""
                width="100%"
                height={300}
                style={{ objectFit: "cover" }}
              />
              <span
                style={{
                  position: "absolute",
                  top: 0,
                  right: 0,
                  cursor: "pointer",
                }}
                onClick={() => handleDelete(v.name)}
              >
                X
              </span>
            </Col>
          );
        })}
      </Row>
    </div>
  );
}

export default App;
